'use client';

import { type ChangeEvent, type FormEvent, useEffect, useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { updateParentReplyReviewStatus } from '@/services/api';
import diff from 'microdiff';
import type { IDifference } from '@/interfaces';
import useToast from '@/hooks/useToast';
import { getDiffData } from '@/lib/tool';
import Box from '@/app/[locale]/admin/common/box';
import Spinner from '@/app/[locale]/component/spinner/spinner';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';

export default function UpdateParentReplyReviewState({
  source,
  translatedFields,
}: {
  source: {
    id: string;
    reviewState?: string;
  };
  translatedFields: PrefixedTTranslatedFields<'replyAdminPage'>;
}) {
  const { show } = useToast();
  const [form, setForm] = useState<{
    reviewState?: string;
    reviewReason?: string;
  }>({
    reviewState: source.reviewState,
    reviewReason: '',
  });
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const [isDisabledSave, setIsDisabledSave] = useState(true);

  const updateParentReplyReviewStatusMutation = useMutation(
    updateParentReplyReviewStatus,
  );

  useEffect(() => {
    const diffData = diff(
      {
        reviewState: source.reviewState,
        reviewReason: '',
      },
      form,
    );
    setDifferenceData(diffData);
    setIsDisabledSave(diffData.length === 0);
  }, [form, source.reviewState]);

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      const data = getDiffData(differenceData) as any;

      const id = source.id;
      await updateParentReplyReviewStatusMutation.mutateAsync({
        id,
        data,
      });

      show({
        type: 'SUCCESS',
        message: translatedFields.operate.saveCompleted,
      });
    } catch (e) {
      updateParentReplyReviewStatusMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    } finally {
      setDifferenceData([]);
    }
  }

  function onChange(
    e: ChangeEvent<HTMLSelectElement | HTMLInputElement | HTMLTextAreaElement>,
  ) {
    const name = e.target.name;
    const value = e.target.value;
    setForm({ ...form, [name]: value });
  }

  return (
    <Box>
      <form onSubmit={onClickSave} className="vstack gap-4">
        <div>
          <label className="form-label">
            {translatedFields.properties.reviewState}
          </label>
          <select
            name="reviewState"
            value={form.reviewState}
            onChange={onChange}
            className="form-select"
            aria-label="reviewState"
            placeholder={translatedFields.tip.reviewStatePlaceholder}
          >
            {['APPROVED', 'DENIED', 'PENDING', 'CLOSE'].map((key) => {
              return (
                <option key={key} value={key}>
                  {(translatedFields as any).enums.reviewState[key]}
                </option>
              );
            })}
          </select>
        </div>

        <div>
          <label className="form-label">
            {translatedFields.properties.reviewReason}
          </label>
          <textarea
            rows={1}
            value={form.reviewReason}
            name="reviewReason"
            onChange={onChange}
            className="form-control"
            placeholder={translatedFields.tip.reviewReasonPlaceholder}
          />
        </div>

        <button
          type="submit"
          disabled={
            updateParentReplyReviewStatusMutation.isLoading || isDisabledSave
          }
          className="btn btn-success col col-lg-2 my-4"
        >
          {updateParentReplyReviewStatusMutation.isLoading && (
            <Spinner classs="me-2" />
          )}
          {translatedFields.operate.update}
        </button>
      </form>
    </Box>
  );
}
